package com.canyou.config;

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * 配置方法 @PathVariable 和 @RequestParam 参数校验, 需要在 Controller 上配合 @Validated使用
 *
 * @author fy
 * @date 2018-07-13 16:18
 */
@Configuration
public class MethodValidationPostProcessorConfig {

    /**
     * 配置可以处理方法参数 @PathVariable 和 @RequestParam 参数校验
     *
     * @return
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        /**
         * 默认是普通模式，会返回所有的验证不通过信息集合
         */
        return new MethodValidationPostProcessor();
    }

    /**
     * 配置校验 fail_fast(尽快出错返回失败)
     *
     * @return
     */
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .addProperty("hibernate.validator.fail_fast", "true")
                .buildValidatorFactory();

        return validatorFactory.getValidator();
    }
}
